# NOT TESTED! From old pi3diamond
import logging
import threading

#basename = 'D:/data/LabBook/2011-07-22/script_stable_fid3pi2/2011-07-22_nv33_fid3pi2_'

from utility import StoppableThread, get_timestamp_string

class PeriodicSaver( StoppableThread ):

    """
    Provides periodic saving of data.
    
    Example of usage:
    
        periodic_saver = PeriodicSaver(target=my_measurement, basename='my_file', interval=600.)
        periodic_saver.start()
        ...
        periodic_saver.stop()
    """

    def __init__(self, target, basename, interval=300.):
        StoppableThread.__init__(self)
        
        self.target   = target
        self.basename = basename
        self.interval = interval

    def run(self):
        while True:
            threading.currentThread().stop_request.wait(self.interval)
            if threading.currentThread().stop_request.isSet():
                logging.getLogger().info('stopping PeriodicSaver')
                break
            logging.getLogger().info('saving data...')
            self.target.save(self.basename + get_timestamp_string() + '.pys')

